<template>
    <div
        :class="['w-full p-24 box-border', { 'min-loading-height': isLoading }]"
        v-loading="isLoading"
        element-loading-text="加载中....."
    >
        <template v-if="!isLoading">
            <!-- 表单 -->
            <div class="w-full flex-between-items-box join-member-wrapper">
                <!-- 活动信息 -->
                <div class="join-member-container h-full card-style common-shadow relative">
                    <!-- 活动信息 -->
                    <div class="card-title mb-30 w-full flex-between-items-box">
                        <span>活动信息</span>
                        <Icon
                            name="Edit"
                            :class="['cursor-pointer', isEdit ? 'text-primary' : 'text-t-default']"
                            :size="20"
                            @click="isEdit = true"
                        />
                    </div>
                    <!-- 表单 -->
                    <el-form
                        class="flex-col"
                        ref="ruleFormRef"
                        :model="ruleForm"
                        :rules="rules"
                        :disabled="!isEdit"
                        label-width="130px"
                        status-icon
                    >
                        <!-- 活动规则 -->
                        <el-form-item label="活动规则：" >
                            <p :class="[isEdit ? 'text-t-default' : 'text-t-secondary']">首次消费成为新会员，将发放礼品</p>
                        </el-form-item>
                        <!-- 活动说明 -->
                        <el-col :span="22">
                            <el-form-item label="活动说明：" prop="activityDesc">
                                <el-input
                                    v-model="ruleForm.activityDesc"
                                    type="textarea"
                                    placeholder="请输入活动说明..."
                                    rows="7"
                                />
                            </el-form-item>
                        </el-col>
                        <!-- 活动对象 -->
                        <el-form-item label="活动对象：">
                            <p :class="[isEdit ? 'text-t-default' : 'text-t-secondary']">新会员</p>
                        </el-form-item>
                        <!-- 是否通知 -->
                        <el-col :span="18">
                            <el-form-item label="是否通知：">
                                <el-switch v-model="ruleForm.isNotice"/>
                                <el-popover
                                    placement="right"
                                    trigger="hover"
                                    content="将以短信的形式通知该会员"
                                    width="150"
                                >
                                    <template #reference>
                                        <Icon name="Warning" class="ml-12 cursor-pointer text-t-default"/>
                                    </template>
                                </el-popover>
                            </el-form-item>
                        </el-col>
                        <!-- 活动礼品 -->
                        <el-col :span="16">
                            <el-form-item label="活动礼品：" prop="articlePictureList">
                                <el-button type="primary">选择礼品</el-button>
                            </el-form-item>
                        </el-col>
                        <div class="absolute right-20 bottom-20">
                            <el-button round>取消</el-button>
                            <el-button round type="primary">保存</el-button>
                        </div>
                    </el-form>
                    <img src="@/assets/images/memberOperation/joinMember.png" class="absolute right-0 activity-icon"/>
                </div>
                <!-- 活动分析 -->
                <div class="join-member-container h-full card-style common-shadow">
                    <!-- 活动分析 -->
                    <div class="card-title mb-30 w-full flex-between-items-box">
                        <span>活动分析</span>
                        <Icon name="Refresh" class="cursor-pointer text-t-default" :size="20"/>
                    </div>
                    <div class="distribution-details w-full rounded-14 p-24 box-border">
                        <div class="text-t-title text-14 mb-20">礼品发放明细</div>
                        <el-table :data="tableData" style="width: 100%">
                            <el-table-column prop="memberCardId" label="会员卡号" width="110" />
                            <el-table-column prop="userPhone" label="会员手机号" width="150" />
                            <el-table-column prop="distributeGifts" label="发放礼品" width="180" />
                            <el-table-column prop="distributionTime" label="发放时间" />
                        </el-table>
                        <div class="w-full flex-end-box mt-24">
                            <el-pagination background layout="prev, pager, next" :total="1000" />
                        </div>
                    </div>
                    <div class="distribution-details w-full rounded-14 mt-24 box-border p-24">
                        <EChartsContainer title="近 7 日发放明细" :options="sevenDayFlowOptions" id="sevenDaySendFlowECharts"/>
                    </div>
                </div>
            </div>
        </template>
    </div>
</template>

<script setup lang="ts">
import { reactive, ref } from 'vue'
import { useRouter } from 'vue-router'
import type { FormInstance, FormRules } from 'element-plus'
import { ArticleDetail,
    ArticleParams,
    httpAddArticle,
    httpArticleDetail,
    httpUpdateArticle } from '@api/module/brandPromotion'
import { ElMessages, FormRule, timeout } from '@utils/methods'
import Icon from '@/components/Icon/index.vue'
import dayjs from 'dayjs'
import EChartsContainer from '@components/EChartsContainer/index.vue'

const router = useRouter()

// 页面加载
const isLoading = ref(true)

// 是否编辑
const isEdit = ref(false)

// 表单实例
const ruleFormRef = ref<FormInstance>()

// 表单数据
const ruleForm = reactive<any>({
    activityDesc: '',
    isNotice: false,
    activityGift: null
})

// 表单校验
const rules = <FormRules>{
    activityDesc: [FormRule.requireRule('请输入活动描述')],
    articleContent: [FormRule.requireRule('请输入文章内容')],
    articlePictureList: [FormRule.requireRule('请上传文章图片')]
}

const tableData = [
    {
        memberCardId: 'X0000113',
        userPhone: '18831845005',
        distributeGifts: '20 积分',
        distributionTime: '2023-04-21 22:29:56'
    },
    {
        memberCardId: 'X0000112',
        userPhone: '14779427242',
        distributeGifts: '20 积分',
        distributionTime: '2023-04-21 22:29:56'
    },
    {
        memberCardId: 'X0000111',
        userPhone: '18283189711',
        distributeGifts: '20 积分',
        distributionTime: '2023-04-21 22:29:56'
    },
    {
        memberCardId: 'X0000110',
        userPhone: '14737366601',
        distributeGifts: '20 积分',
        distributionTime: '2023-04-21 22:29:56'
    },
    {
        memberCardId: 'X0000109',
        userPhone: '14737366601',
        distributeGifts: '20 积分',
        distributionTime: '2023-04-21 22:29:56'
    }
]

// 近 7 日发放量变化
const sevenDayFlowOptions = ref({})
// 文章详情
const articleDetail = ref<ArticleDetail>()

setTimeout(async () => {
    await timeout(500)
    await nextTick()
    /**
     * 近 7 日访问流量
     * */
    // 近 7 日日期
    const sevenDay = []
    for (let day = 0; day <= 6; day++) {
        sevenDay.push(dayjs().subtract(day, 'day').format('MM-DD'))
    }
    sevenDayFlowOptions.value = {
        // 提示框
        tooltip: {
            trigger: 'item'
        },
        xAxis: {
            type: 'category',
            data: sevenDay.reverse()
        },
        yAxis: {
            type: 'value',
            splitLine: {
                lineStyle: {
                    type: 'dashed'
                }
            }
        },
        series: [
            {
                data: [4522, 3841, 6649, 7724, 4342, 3387, 3112],
                type: 'line',
                smooth: true
            }
        ]
    }
}, 200)

// 获取文章详情 编辑 / 详情
const getArticleDetail = () => {
    httpArticleDetail({
        articleId: 1
    }).then(({ success, data }) => {
        if (success) {
            articleDetail.value = data
            const { articleTitle, articleContent, articlePictureList } = data
            ruleForm.articleTitle = articleTitle
            ruleForm.articleContent = articleContent.replaceAll('\\n', '<br/>')
            ruleForm.articlePictureList = articlePictureList
        }
    }).finally(async () => {
        await timeout(500)
        isLoading.value = false
    })
}

getArticleDetail()

// 取消
const cancel = () => {
    router.push({
        path: '/BrandPromotion'
    })
}

// 提交表单参数
type SubmitForm = (formEl: FormInstance | undefined, type: 'save' | 'release') => void

// 提交表单
const submitForm: SubmitForm = async (formEl, type) => {
    if (!formEl) return
    await formEl.validate(valid => {
        if (valid) {
            // pageType.value === 'add' ? addArticle(type) : updateArticle(type)
        }
    })
}

// 新增文章
const addArticle = (type: 'save' | 'release') => {
    const { articleTitle, articleContent, author, articlePictureList } = ruleForm
    // 请求参数
    const params: ArticleParams = {
        articleTitle,
        articleContent,
        author,
        releaseStatus: type === 'save' ? 0 : 1,
        articlePictureList: articlePictureList.map((item: any) => ({
            name: item.name,
            url: item.response.data
        }))
    }
    // 文章添加
    httpAddArticle(params).then(({ success }) => {
        if (success) {
            ElMessages.success('新增成功！')
            cancel()
        } else {
            ElMessages.warning('新增失败！')
        }
    })
}

// 更新文章 保存草稿 | 确认发布
const updateArticle = (type: 'save' | 'release') => {
    const { articleTitle, articleContent, articlePictureList } = ruleForm
    // 更新数据
    const updateParams = {
        ...articleDetail.value,
        articleTitle,
        articleContent,
        createdTime: dayjs(articleDetail.value?.createdTime).format('YYYY-MM-DD HH:mm:ss'),
        releaseStatus: type === 'save' ? 0 : 1,
        articlePictureList: articlePictureList.map((item: any) => ({
            name: item.name,
            url: item.response ? item.response.data : item.url
        }))
    }
    // 文章添加
    httpUpdateArticle(<ArticleDetail>updateParams).then(({ success }) => {
        if (success) {
            ElMessages.success('修改成功！')
            cancel()
        } else {
            ElMessages.warning('修改失败！请重试')
        }
    })
}

</script>

<style lang="less" scoped>
.join-member-wrapper {
    height: calc(100vh - 118px);

    .join-member-container{
        width: calc((100% - 24px) / 2);

        .el-form{
            &:first-child{

                .el-form-item {
                @apply mt-20;
                }
            }
        }
    }

    .activity-icon{
        bottom: 140px;
        width: 170px;
        height: 170px;
    }

    .el-form-item{
        @apply mt-34;
    }
}

.distribution-details {
    height: 45%;
    border: 1px solid #BFBFBF;
}
</style>
